package com.example.coding_problem.Fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.coding_problem.Distance;
import com.example.coding_problem.MyExtendableListViewAdapter;
import com.example.coding_problem.R;
import com.example.coding_problem.Threshold_stl;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;

import static android.support.constraint.Constraints.TAG;

public class Threshold_setting extends Fragment{
    private MyExtendableListViewAdapter adapter;
    private ExpandableListView expandableListView;
    private List<Distance> distances = new ArrayList<>();
   private StaAdaoter staAdaoter;
    private TextView Serial;
    private TextView Seria2;
    private TextView tv_people;
    private List<Threshold_stl> threshold_list;
    private Button bu_xq;
    public Threshold_setting() {
    }
    private void showSetDeBugDialog(){
        AlertDialog.Builder setDeBugDialog = new AlertDialog.Builder(getContext());
        //获取界面
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.statistics, null);
        //将界面填充到AlertDiaLog容器
        setDeBugDialog.setView(dialogView);
        //初始化控件
        final ListView statistics_list= dialogView.findViewById(R.id.statistics_list);
         Button return1=dialogView.findViewById(R.id.return1);
        final TextView tv_zrs=dialogView.findViewById(R.id.tv_zrs);
        //取消点击外部消失弹窗
        setDeBugDialog.setCancelable(false);
        //创建AlertDiaLog
        setDeBugDialog.create();
        //AlertDiaLog显示
        final AlertDialog customAlert = setDeBugDialog.show();
        return1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customAlert.dismiss();
            }
        });
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogService0 service = retrofit.create(BlogService0.class);
        Call<ResponseBody> call = service.getBlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Gson gson = new Gson();
                threshold_list = new ArrayList<>();
                Threshold_stl carlist = null;
                try {
                    carlist = gson.fromJson(response.body().string(), Threshold_stl.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                threshold_list.add(carlist);
                int j=0;
                for (int i=0;i<threshold_list.get(0).getData().size();i++){
                    j=j+threshold_list.get(0).getData().get(i).getPersonNum();
                }
                tv_zrs.setText(j+"");
                if (staAdaoter == null){
                    staAdaoter = new StaAdaoter();
                    statistics_list.setAdapter(staAdaoter);
                }else {
                    staAdaoter.notifyDataSetChanged();
                }

            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
    class StaAdaoter extends BaseAdapter {
        @Override
        public int getCount() {
            return threshold_list.get(0).getData().size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View view1 = (View) View.inflate(getContext(), R.layout.statistics_one, null);
            Serial = (TextView) view1.findViewById(R.id.Serial);
            Seria2 = (TextView) view1.findViewById(R.id.Seria2);
            tv_people=(TextView)view1.findViewById(R.id.tv_people);
            Serial.setText(i+1+"");
            Seria2.setText(threshold_list.get(0).getData().get(i).getCarId()+"");
            tv_people.setText(threshold_list.get(0).getData().get(i).getPersonNum()+"");
            return view1;
        }
    }
    public interface BlogService1 {
        @POST("pubcar")
        Call<ResponseBody> getBlog1(@Body RequestBody user);
    }
    public interface BlogService0 {
        @GET("getCarPersonNum")
        Call<ResponseBody> getBlog();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.open, container, false);
        initView(view);
        initData(0);
        initData(1);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 3000);
        return view;
    }

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            distances = new ArrayList<>();
            initData(0);
            initData(1);
            handler.postDelayed(this, 3000);
        }
    };

    private void initData(final int i) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Map<String, Integer> map = new HashMap<>();
        map.put("CarId", i);
        final Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(gson.toJson(map), MediaType.parse("application/json;charset=utf-8"));
        BlogService1 service1 = retrofit.create(BlogService1.class);
        Call<ResponseBody> call = service1.getBlog1(requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Gson gson = new Gson();
                    Distance carlist = gson.fromJson(response.body().string(), Distance.class);
                    distances.add(carlist);
                    //每次点击下拉之后，都会自动缩回去，这就是判断之后不会，点击缩回去的方法
                    if (distances.size() == 2 && adapter != null) {
                        adapter.updateData(distances);
                        if (expandableListView.collapseGroup(0))
                            expandableListView.expandGroup(0);
                        if (expandableListView.collapseGroup(1))
                            expandableListView.expandGroup(1);
                    }
                    if (distances.size() == 2 && adapter == null) {
                        Collections.sort(distances.get(0).getData(), new Order());
                        adapter = new MyExtendableListViewAdapter(distances);
                        expandableListView.setAdapter(adapter);
                        Log.i(TAG, "onResponse: " + distances.get(0).getData().get(0).getDistance());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
    private void initView(View view) {
        expandableListView = view.findViewById(R.id.expend_list);
        bu_xq=view.findViewById(R.id.bu_xq);
        bu_xq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                threshold_list = new ArrayList<>();
                showSetDeBugDialog();
            }
        });
    }
    public class Order implements Comparator<Distance.DataBean> {
        @Override
        public int compare(Distance.DataBean d0, Distance.DataBean d1) {
            return (int) (d1.getDistance() - d0.getDistance());
        }
    }
}